import { Table, type TableColumnsType } from 'antd';
import { useCallback, useEffect, useState } from 'react';
import type * as React from 'react';
import { useCustomerState } from '../../stores/CustomerStore.ts';
import CustomerCardModal from './CustomerCardModal.tsx';

interface DataType {
  key: React.Key;
  cardID: string;
  savingID: number;
  currency: string;
  openDate: string;
  openMoney: number;
  balance: number;
  isReportLoss: boolean;
}

const columns: TableColumnsType<DataType> = [
  { title: '卡号', dataIndex: 'cardID', width: '18%' },
  {
    title: '存款类型',
    dataIndex: 'savingID',
    render: (savingID: number) => {
      const savingTypes: Record<number, string> = {
        1: '活期',
        2: '定期一年',
        3: '定期二年',
        4: '定期三年',
        5: '定活两便',
        6: '零存整取一年',
        7: '零存整取二年',
        8: '零存整取三年',
      };
      return savingTypes[savingID] || '未知';
    },
    filters: [
      { text: '活期', value: 1 },
      { text: '定期一年', value: 2 },
      { text: '定期二年', value: 3 },
      { text: '定期三年', value: 4 },
      { text: '定活两便', value: 5 },
      { text: '零存整取一年', value: 6 },
      { text: '零存整取二年', value: 7 },
      { text: '零存整取三年', value: 8 },
    ],
    onFilter: (value, record) => record.savingID === value,
  },
  {
    title: '货币',
    dataIndex: 'currency',
    filters: [
      { text: 'RMB', value: 'RMB' },
      { text: 'USD', value: 'USD' },
    ],
    filterMode: 'tree',
    onFilter: (value, record) => record.currency.startsWith(value as string),
  },
  {
    title: '开卡日期',
    dataIndex: 'openDate',
    sorter: (a, b) =>
      new Date(a.openDate).getTime() - new Date(b.openDate).getTime(),
  },
  {
    title: '开卡金额',
    dataIndex: 'openMoney',
    sorter: (a, b) => a.openMoney - b.openMoney,
  },
  {
    title: '余额',
    dataIndex: 'balance',
    sorter: (a, b) => a.balance - b.balance,
  },
  {
    title: '是否挂失',
    dataIndex: 'isReportLoss',
    render: (isReportLoss: boolean) => (isReportLoss ? '是' : '否'),
    filters: [
      { text: '是', value: true },
      { text: '否', value: false },
    ],
    onFilter: (value, record) => record.isReportLoss === value,
  },
];

function CustomerCard() {
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [selectedCardID, setSelectedCardID] = useState('');
  const [cards, setCards] = useState<DataType[]>([]);
  const { customer } = useCustomerState();

  const fetchCards = useCallback(() => {
    if (customer) {
      fetch(`http://localhost:8000/cards/by_customer/${customer.customerID}`)
        .then((response) => response.json())
        .then((data) => {
          const formattedData = data.map((card: any) => ({
            key: card.cardID,
            cardID: card.cardID,
            savingID: card.savingID,
            currency: card.curID,
            openDate: card.openDate,
            openMoney: card.openMoney,
            balance: card.balance,
            isReportLoss: card.IsReportLoss === 1,
          }));
          setCards(formattedData);
        });
    }
  }, [customer]);

  useEffect(() => {
    fetchCards();
  }, [fetchCards]);

  const handleRowClick = (record: DataType) => {
    setSelectedCardID(record.cardID);
    setIsModalVisible(true);
  };

  const handleCancel = () => {
    setIsModalVisible(false);
  };

  const handleOperationSuccess = () => {
    fetchCards();
  };

  return (
    <>
      <Table<DataType>
        columns={columns}
        dataSource={cards}
        onRow={(record) => ({
          onClick: () => handleRowClick(record),
        })}
      />
      {selectedCardID && (
        <CustomerCardModal
          visible={isModalVisible}
          onCancel={handleCancel}
          cardID={selectedCardID}
          onSuccess={handleOperationSuccess}
        />
      )}
    </>
  );
}

export default CustomerCard;
